package org.fyp.synchrona.blog.service;

import com.google.gdata.client.Query;
import com.google.gdata.client.blogger.BloggerService;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.TextContent;
import com.google.gdata.util.ServiceException;

import java.net.URL;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import org.fyp.synchrona.blog.communication.Communication;
import org.fyp.synchrona.blog.service.util.NewData;
import org.fyp.synchrona.blog.service.util.OldData;
import org.fyp.synchrona.core.info.impl.ICommonDataObject;

import org.fyp.synchrona.util.IAccount;
import org.fyp.synchrona.util.IUpdate;

public class Updater {

	/*
	 * These parameters for blogger status update
	 */
	private static final String METAFEED_URL = "http://www.blogger.com/feeds/default/blogs";

	private static final String FEED_URI_BASE = "http://www.blogger.com/feeds";
	private static final String POSTS_FEED_URI_SUFFIX = "/posts/default";
	private static final String COMMENTS_FEED_URI_SUFFIX = "/comments/default";

	private static String feedUri;
	
	static final Logger logger = Logger.getLogger(Updater.class);
	/*
	 * 
	 */
	String userName;

	String password;

	Communication com;

	OldData OldDataObj;

	NewData newDataObj;

	NewDataProcessor ndp;

	OldDataProcessor odp;

	public Updater(String userName, String password) {
		this.userName = userName;
		this.password = password;
		com = new Communication(userName, password);
		OldDataObj = new OldData();
		newDataObj = new NewData();
		odp = new OldDataProcessor(OldDataObj);
		ndp = new NewDataProcessor(OldDataObj, newDataObj);
	}
    
	public void startUpdate(IUpdate updateObj) {

		try {
			logger.info("[BLOGGER] updatetype ::"+updateObj.getUpdateType());
			if (updateObj.getUpdateType() == "STS") {
				logger.info("[BLOGGER] -------------------------UPDATE Received is Status Message----------------");
				logger.info("[BLOGGER] status ::"+updateObj.getCdo().getSTATUS());
				logger.info("[BLOGGER] username ::"+userName);
				logger.info("[BLOGGER] password ::"+password);
				updateStatus(updateObj.getCdo(), this.userName, this.password,updateObj.getServiceType());
			} else if (updateObj.getUpdateType() == "PROFILE") {
				logger.info("[BLOGGER] -------------------------UPDATE Received is Profile Update----------------");
				logger.info("[BLOGGER] username ::"+userName);
				logger.info("[BLOGGER] password ::"+password);
				updateProfile(updateObj.getCdo(), this.userName, this.password);
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void updateStatus(ICommonDataObject cdo, String userName,
			String password, String serviceType) {

		new Blogpost().updateBlogger(cdo.getSTATUS(), userName, password,
				serviceType);

	}

	private void updateProfile(ICommonDataObject cdo, String userName,
			String password) throws ClientProtocolException, IOException {
		HttpGet httpgetHome = new HttpGet(com.getLoginURL());
		HttpResponse response = com.getHttpClient().execute(httpgetHome);
		HttpEntity entity = response.getEntity();
		// System.out.println("Status: " + response.getStatusLine());
		if (entity != null) {
			entity.consumeContent();
		}

		HttpGet httpgetEdit = new HttpGet(
				"http://www.blogger.com/edit-profile.g");
		response = com.getHttpClient().execute(httpgetEdit);
		entity = response.getEntity();
		// System.out.println("Status: " + response.getStatusLine());
		if (entity != null) {
			String editPage = EntityUtils.toString(entity);
			odp.retriveOldParameters(editPage);
			entity.consumeContent();
		}
		ndp.createUpdateObj(cdo);
		updateSite();
	}

	private void updateSite() throws ClientProtocolException, IOException {
		HttpPost httpostProfile = new HttpPost(
				"http://www.blogger.com/edit-profile.do");
		List nvps = new ArrayList();
		

		
		nvps.add(new BasicNameValuePair("securityToken", newDataObj.getSecurityToken()));
		
		logger.info("[BLOGGER] securityToken ::"+newDataObj.getSecurityToken());
		
		nvps.add(new BasicNameValuePair("security_token", newDataObj.getSecurity_Token()));
		
		logger.info("[BLOGGER] security_token ::"+newDataObj.getSecurity_Token());
		
		nvps.add(new BasicNameValuePair("enable", "true"));
		
		//System.out.println("enable ::"+newDataObj.getEnable());
		
		nvps.add(new BasicNameValuePair("showName", "true"));
		
		//System.out.println("showName ::"+newDataObj.getShowname());
		
		nvps.add(new BasicNameValuePair("showEmail", "true"));
		
		//System.out.println("showEmail ::"+newDataObj.getShowemail());
		
		nvps.add(new BasicNameValuePair("email", newDataObj.getEmail()));
		
		logger.info("[BLOGGER] email ::"+newDataObj.getEmail());
		
		nvps.add(new BasicNameValuePair("widget.displayname", newDataObj.getWidget_displayname()));
		
		logger.info("[BLOGGER] widget.displayname ::"+newDataObj.getWidget_displayname());
		
		nvps.add(new BasicNameValuePair("firstname", newDataObj.getFirstName()));
		
		logger.info("[BLOGGER] firstname ::"+newDataObj.getWidget_displayname());
		
		nvps.add(new BasicNameValuePair("lastname", newDataObj.getLastName()));

		nvps.add(new BasicNameValuePair("photourl", ""));
		
		nvps.add(new BasicNameValuePair("photowidth", ""));
		
		nvps.add(new BasicNameValuePair("photoheight", ""));
		

		nvps.add(new BasicNameValuePair("imageFileName", ""));
		
		
		nvps.add(new BasicNameValuePair("USIradio", "on"));
		
		nvps.add(new BasicNameValuePair("USIerror", ""));

		nvps.add(new BasicNameValuePair("audioclipurl", ""));
		
		nvps.add(new BasicNameValuePair("gender", "FEMALE"));
		
		//System.out.println("GENDER ::"+newDataObj.getGender());
		
		nvps.add(new BasicNameValuePair("birthmonth", newDataObj.getBirthmonth()));
		
		logger.info("[BLOGGER] BIRTH MONTH ::"+newDataObj.getBirthmonth());
		
		nvps.add(new BasicNameValuePair("birthday", newDataObj.getBirthday()));
		
		logger.info("[BLOGGER] BIRTH DAY ::"+newDataObj.getBirthday());
		
		nvps.add(new BasicNameValuePair("birthyear", newDataObj.getBirthyear()));
		
		logger.info("[BLOGGER] BIRTH YEAR ::"+newDataObj.getBirthyear());
		
		nvps.add(new BasicNameValuePair("showAstrologicalSigns",  "true"));
		
		nvps.add(new BasicNameValuePair("url", newDataObj.getUrl()));
		
		logger.info("[BLOGGER] URL ::"+newDataObj.getUrl());
		
		nvps.add(new BasicNameValuePair("wishlisturl", newDataObj.getUrl()));
		
		//System.out.println("wishlisturl ::"+newDataObj.getWishlisturl());
		
		nvps.add(new BasicNameValuePair("imusername", ""));
		
		nvps.add(new BasicNameValuePair("imnetwork", "_nil_"));
		
		nvps.add(new BasicNameValuePair("widget.city", newDataObj.getWidget_city()));
		
		logger.info("[BLOGGER] widget.city ::"+newDataObj.getWidget_city());
		
		nvps.add(new BasicNameValuePair("widget.state", newDataObj.getWidget_state()));
		
		logger.info("[BLOGGER] widget.state ::"+newDataObj.getWidget_state());
		
		nvps.add(new BasicNameValuePair("widget.country", newDataObj.getWidget_country()));
		
		logger.info("[BLOGGER] widget.country ::"+newDataObj.getWidget_country());
		
		nvps.add(new BasicNameValuePair("ind", "_nil_"));
		
		nvps.add(new BasicNameValuePair("occupation", newDataObj.getOccupation()));
		
		logger.info("[BLOGGER] occupation ::"+newDataObj.getOccupation());
		
		nvps.add(new BasicNameValuePair("interests", newDataObj.getInterests()));
		
		logger.info("[BLOGGER] interests ::"+newDataObj.getInterests());
		
		nvps.add(new BasicNameValuePair("widget.aboutme", newDataObj.getWidget_aboutme()));
		
		logger.info("[BLOGGER] widget.aboutme ::"+newDataObj.getWidget_aboutme());
		
		
		nvps.add(new BasicNameValuePair("movies", newDataObj.getMovies()));
		
		logger.info("[BLOGGER] movies ::"+newDataObj.getMovies());
		
		
		nvps.add(new BasicNameValuePair("music", newDataObj.getMusic()));
		
		logger.info("[BLOGGER] music ::"+newDataObj.getMusic());
		
		
		nvps.add(new BasicNameValuePair("books", newDataObj.getBooks()));
		
		logger.info("[BLOGGER] books ::"+newDataObj.getBooks());
		
		
		nvps.add(new BasicNameValuePair("wackyQuestion", newDataObj.getWackyQuestion()));
		
		logger.info("[BLOGGER] wackyQuestion ::"+newDataObj.getWackyQuestion());
		
		
		nvps.add(new BasicNameValuePair("wackyAnswer", newDataObj.getWackyAnswer()));
		
		logger.info("[BLOGGER] wackyAnswere ::"+newDataObj.getWackyAnswer());
		
		
		nvps.add(new BasicNameValuePair("submitButton", "Save"));
		
		

		httpostProfile.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		HttpResponse response = com.getHttpClient().execute(httpostProfile);
		HttpEntity entity = response.getEntity();
		logger.info("[BLOGGER] Profile update ::" + response.getStatusLine());
		if (entity != null) {
			//System.out.println("Profile edit page: "
			//		+ EntityUtils.toString(entity));
			entity.consumeContent();
		}

		com.getHttpClient().getConnectionManager().shutdown();

	}

}
